package com.tuozixuan.code.ve;

import java.io.StringWriter;
import java.util.Map;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

public enum VEContext {
	
	INSTANCE;
	
	private VelocityEngine ve;
	private VEContext() {
		try {
            ve = new VelocityEngine();
            ve.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.NullLogChute");
            ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
            ve.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
            ve.setProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8");
            ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
            ve.init();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
	}
	
	public String parseTemplate(String vmFilePath, Map<String, Object> param) {
        Template t;
        try {
            t = ve.getTemplate(vmFilePath);
            VelocityContext ctx = new VelocityContext(param);
            StringWriter sw = new StringWriter();
            t.merge(ctx, sw);
            return sw.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
